package com.interesting.client.UI.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.interesting.base.http.HttpUtil;
import com.interesting.base.utils.SQLiteUtil;
import com.interesting.client.UI.home.CommentActivity;
import com.interesting.client.adapter.UserMesgListAdapter;
import com.interesting.client.application.AppHolder;
import com.interesting.client.bean.Message;
import com.interesting.client.support.pulltorefresh.PullToRefreshBase;
import com.interesting.client.support.pulltorefresh.PullToRefreshBase.OnLastItemVisibleListener;
import com.interesting.client.support.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.interesting.client.support.pulltorefresh.PullToRefreshListFragment;

/**
 * 
 * 
 * 我发表 的 fragment
 */
public class MyNewsFragment extends PullToRefreshListFragment implements OnRefreshListener<ListView>,
		OnLastItemVisibleListener {

	private UserMesgListAdapter mesgAdapter;
	private List<Message> mesg_data = new ArrayList<Message>();
	private int currentPage = 1;
	private int totalPage;
	private static String TYPE = "content_type";// 显示信息的类别

	public MyNewsFragment newInstance(String type) {
		Bundle args = new Bundle();
		args.putString(TYPE, type);
		MyNewsFragment fragment = new MyNewsFragment();
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return super.onCreateView(inflater, container, savedInstanceState);

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		mesgAdapter = new UserMesgListAdapter(getSherlockActivity(), mesg_data);

		pullToRefreshListView.setOnRefreshListener(this);
		pullToRefreshListView.setOnLastItemVisibleListener(this);

		getListView().setAdapter(mesgAdapter);
		if (getCurrentState(savedInstanceState) == FIRST_TIME_START) {
			pullToRefreshListView.startRefreshNow();
			this.hide();
		}
		/** 点击listview的item 进入查看评论界面 */
		getListView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				Intent intent_comment = new Intent(getSherlockActivity(), CommentActivity.class);
				intent_comment.putExtra("message", mesg_data.get(position - 1));
				startActivity(intent_comment);
			}
		});

	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("data", "mesg_data");
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		currentPage = 1;
		new MessageRefresh().execute(AppHolder.getInsatnce().user.getUserId(), currentPage + "");
	}

	@Override
	public void onLastItemVisible() {
		if (currentPage < totalPage) {
			showFooterView();
			currentPage++;
			new MessageRefresh().execute(AppHolder.getInsatnce().user.getUserId(), currentPage + "");
		}
	}

	@Override
	public void onResume() {
		currentPage = 1;
		new MessageRefresh().execute(AppHolder.getInsatnce().user.getUserId(), currentPage + "");
		super.onResume();
	}

	/** 我发表的 */
	class MessageRefresh extends AsyncTask<String, Void, String> {
		
		private SQLiteUtil sqllite;
		public final String[] allColumns = { SQLiteUtil.HOME_ID, SQLiteUtil.HOME_JOKEID, SQLiteUtil.HOME_JOKESTATE };
		
		@Override
		protected String doInBackground(String... params) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("act", "myNewsList");
			map.put("userId", params[0]);
			map.put("currentPage", params[1]);
			return HttpUtil.post(map);
		}

		@Override
		protected void onPostExecute(String result) {
			JSONObject response = HttpUtil.parseResult(result);

			try {
				if (currentPage == 1)
					mesg_data.clear();
				Gson gson = new Gson();
				List<Message> dataList = gson.fromJson(response.getString("dataList"), new TypeToken<List<Message>>() {
				}.getType());
				
				// lite数据库扫描看是否有数据
				String ids = "";
				for (int i = 0; i < dataList.size(); i++) {
					ids += "'" + dataList.get(i).getId() + "'";
					if (i != dataList.size() - 1)
						ids += ",";
				}
				sqllite = AppHolder.getInsatnce().dbAdapter;
				Cursor cursor = sqllite.getWritableDatabase().query(SQLiteUtil.TABLE_JOKE, allColumns,
						"jokeid IN (" + ids + ")", null, null, null, null);
				Log.d("TAG", "已投票数量:" + cursor.getCount() + "");
				cursor.moveToFirst();
				while (!cursor.isAfterLast()) {

					for (int i = 0; i < dataList.size(); i++) {
						if (dataList.get(i).getId().equals(cursor.getString(1))) {
							dataList.get(i).setStatus(Integer.parseInt(cursor.getString(2)));
							break;
						}
					}
					cursor.moveToNext();
				}
				cursor.close();
				
				
				for (int i = 0; i < dataList.size(); i++) {
					mesg_data.add(dataList.get(i));
				}
				currentPage = Integer.parseInt(response.getString("currentPage"));
				totalPage = Integer.parseInt(response.getString("totalPage"));
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				dismissFooterView();
				pullToRefreshListView.onRefreshComplete();
			}
			mesgAdapter.notifyDataSetChanged();

			show();
			super.onPostExecute(result);
		}

	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null) {
			Message mesg = (Message) data.getParcelableExtra("message");
			for (int i = 0; i < mesg_data.size(); i++) {
				if (mesg.getId().equals(mesg_data.get(i).getId())) {
					mesg_data.set(i, mesg);
					break;
				}
			}
			mesgAdapter.notifyDataSetChanged();
		}
	}

}
